/*
 * Part of the NXT bluetooth remote control J2ME applet.
 * Copyright (C) 2007-2008 Alexander Demin, <alexander@demin.ws>
 *
 * This file is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You can redistribute this file and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software Foundation;
 * either version 2 of the License, or (at your discretion) any later version.
 * See the accompanying file "COPYING.txt" for more details.
 */
import java.lang.*;

public class NxtMessage {

   final static public int INCOMING = 0;
   final static public int REQUEST  = 1;

   final static public byte[] RESPONSE_MSG = new byte[] { 0x02, 0x09, 0x00 };

   int type;
   int mailbox;
   String message;
   boolean responseNeeded;

   public class UnknownMessage extends Exception {}

   int getType() { return type; }
   int getMailbox() { return mailbox; }
   String getMessage() { return message; }
   boolean getResponseNeeded() { return responseNeeded; }

   public NxtMessage( int _type, int _mailbox, String _message, boolean _responseNeeded ) {
      type = _type;
      mailbox = _mailbox;
      message = _message;
      responseNeeded = _responseNeeded;
   }

   public NxtMessage( byte[] cmd ) throws UnknownMessage
   {
      if( (cmd[0] & 0x7F) == 0 && cmd[1] == 0x09 ) {

         type = INCOMING;
         mailbox = (int)cmd[3];

         message = new String( cmd, 4, (int)cmd[3] - 1 );

         responseNeeded = cmd[0] == 0x00;

      } else if( (cmd[0] & 0x7F) == 0x02 && cmd[1] == 0x13 ) {

         type = REQUEST;
         message = "";

         mailbox = (int)cmd[2];

      } else
         throw new UnknownMessage();
   }

   public String toString() {
      String s = 
         (type == INCOMING ? "INCOMING" : "REQUEST" ) +
         (responseNeeded ? " (R)" : "") + ": " +
         mailbox + ", " +
         "'" + message + "'" + ", " + 
         message.length()
      ;

      return s;
   }

   public byte[] pack() {

      byte[] cmd = new byte[80];

      cmd[2] = (byte)0x80;
      cmd[3] = (byte)0x09;

      cmd[4] = (byte)mailbox;

      String msg = message + "\0";

      cmd[5] = (byte)( msg.length() & 0xff );

      for( int i = 0; i < msg.length(); i++ )
         cmd[6+i] = (byte)msg.charAt(i);

      cmd[0] = (byte)( (cmd.length - 2) & 0xFF );
      cmd[1] = (byte)( (cmd.length - 2) >> 8 );

      return cmd;
   }
}
